package org.chen.flight.service.flight;

import lombok.extern.slf4j.Slf4j;
import org.chen.common.flight.RoundTripFlightInfo;
import org.chen.common.flight.OneWayFlightInfo;
import org.chen.common.flight.request.FlightSearchRequest;
import org.chen.flight.service.FlightTranslationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class RoundTripFlightProcessService {

    @Autowired
    private FlightTranslationService translationService;

    /**
     * 处理往返航班数据
     */
    public List<RoundTripFlightInfo> processFlights(List<RoundTripFlightInfo> flights, FlightSearchRequest request) {
        if (flights == null || flights.isEmpty()) {
            return flights;
        }

        log.info("开始处理往返航班数据，原始数量: {}", flights.size());

        List<RoundTripFlightInfo> validFlights;
        // 获取 orderTime 的值，假设 orderTime 是字符串类型，按格式解析
        if ("".equals(request.getOrderDate()) || request.getOrderDate() == null) {
            // 1. 基础有效性筛选
            validFlights = flights.stream()
                    .filter(flight -> isFlightValid(flight, request))
                    .collect(Collectors.toList());
        } else {
            // 获取 orderTime 的值，假设 orderTime 是字符串类型，按格式解析
            String orderTimeStr = request.getOrderDate();  // 获取请求中的 orderTime
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime orderTime = LocalDateTime.parse(orderTimeStr, formatter);  // 解析为 LocalDateTime

            // 1. 基础有效性筛选
            validFlights = flights.stream()
                    .filter(flight -> isFlightValid(flight, request))
                    .filter(flight -> flight.getOutboundFlight().getDepartureTime().isAfter(orderTime))  // 过滤掉 orderTime 之前的航班
                    .collect(Collectors.toList());
        }

        log.info("有效性筛选后数量: {}", validFlights.size());

        // 2. 智能去重 - 保留最低价格
        List<RoundTripFlightInfo> deduplicatedFlights = deduplicateFlights(validFlights);
        List<RoundTripFlightInfo> sortedFlights;
        // 3. 排序 - 直飞优先，然后按价格排序
        if (request.getDirectFlight()) {
            sortedFlights = deduplicatedFlights.stream()
                    .sorted(this::compareFlights)
                    .filter(RoundTripFlightInfo::getIsAllDirectFlight)
                    .limit(new Random().nextInt(18, 24))
                    .collect(Collectors.toList());
            log.info("直飞航班处理完成，最终数量: {}", sortedFlights.size());
        } else {
            sortedFlights = deduplicatedFlights.stream()
                    .sorted(this::compareFlights)
                    .limit(new Random().nextInt(18, 24))
                    .collect(Collectors.toList());
            log.info("非直飞航班处理完成，最终数量: {}", sortedFlights.size());
        }

        log.info("处理完成，最终数量: {}", sortedFlights.size());
        return sortedFlights;
    }

    /**
     * 智能去重 - 针对相同往返组合保留最低价格
     */
    public List<RoundTripFlightInfo> deduplicateFlights(List<RoundTripFlightInfo> flights) {
        Map<String, RoundTripFlightInfo> uniqueFlights = new LinkedHashMap<>();

        for (RoundTripFlightInfo flight : flights) {
            String deduplicationKey = generateDeduplicationKey(flight);

            if (!uniqueFlights.containsKey(deduplicationKey)) {
                uniqueFlights.put(deduplicationKey, flight);
            } else {
                RoundTripFlightInfo existingFlight = uniqueFlights.get(deduplicationKey);
                BigDecimal existingPrice = existingFlight.getAdultTotalPrice();
                BigDecimal currentPrice = flight.getAdultTotalPrice();

                if (currentPrice.compareTo(existingPrice) < 0) {
                    uniqueFlights.put(deduplicationKey, flight);
                }
            }
        }

        log.info("去重完成 - 原始: {}, 去重后: {}", flights.size(), uniqueFlights.size());
        return new ArrayList<>(uniqueFlights.values());
    }

    /**
     * 航班有效性检查
     */
    public boolean isFlightValid(RoundTripFlightInfo flight, FlightSearchRequest request) {
        // 检查价格有效性
        if (flight.getAdultTotalPrice() == null || flight.getAdultTotalPrice().compareTo(BigDecimal.ZERO) <= 0) {
            return false;
        }

        // 检查去程和返程完整性
        if (flight.getOutboundFlight() == null || flight.getReturnFlight() == null) {
            return false;
        }

        // 检查去程有效性
        OneWayFlightInfo outbound = flight.getOutboundFlight();
        if (outbound.getFlightNumber() == null || outbound.getFlightNumber().isEmpty() ||
            outbound.getDepartureTime() == null || outbound.getArrivalTime() == null) {
            return false;
        }

        // 检查返程有效性
        OneWayFlightInfo returnFlight = flight.getReturnFlight();
        if (returnFlight.getFlightNumber() == null || returnFlight.getFlightNumber().isEmpty() ||
            returnFlight.getDepartureTime() == null || returnFlight.getArrivalTime() == null) {
            return false;
        }

        return true;
    }

    /**
     * 航班比较排序 - 直飞优先，然后按价格排序
     */
    public int compareFlights(RoundTripFlightInfo a, RoundTripFlightInfo b) {
        // 直飞优先（往返都直飞的优先）
        boolean aIsAllDirect = Boolean.TRUE.equals(a.getIsAllDirectFlight());
        boolean bIsAllDirect = Boolean.TRUE.equals(b.getIsAllDirectFlight());

        if (aIsAllDirect && !bIsAllDirect) {
            return -1;
        } else if (!aIsAllDirect && bIsAllDirect) {
            return 1;
        }

        // 按中转次数排序（中转次数少的优先）
        int transferComparison = Integer.compare(a.getTotalTransferCount(), b.getTotalTransferCount());
        if (transferComparison != 0) {
            return transferComparison;
        }

        // 价格排序
        return a.getAdultTotalPrice().compareTo(b.getAdultTotalPrice());
    }

    /**
     * 生成去重键
     */
    private String generateDeduplicationKey(RoundTripFlightInfo flight) {
        StringBuilder key = new StringBuilder();

        // 去程信息
        OneWayFlightInfo outbound = flight.getOutboundFlight();
        if (outbound != null) {
            key.append("OUT:")
               .append(outbound.getFlightNumber()).append("|")
               .append(formatTimeForKey(outbound.getDepartureTime().toString())).append("|")
               .append(formatTimeForKey(outbound.getArrivalTime().toString())).append("|")
               .append(outbound.getDepartureAirportCode()).append("-")
               .append(outbound.getArrivalAirportCode()).append(";");
        }

        // 返程信息
        OneWayFlightInfo returnFlight = flight.getReturnFlight();
        if (returnFlight != null) {
            key.append("RET:")
               .append(returnFlight.getFlightNumber()).append("|")
               .append(formatTimeForKey(returnFlight.getDepartureTime().toString())).append("|")
               .append(formatTimeForKey(returnFlight.getArrivalTime().toString())).append("|")
               .append(returnFlight.getDepartureAirportCode()).append("-")
               .append(returnFlight.getArrivalAirportCode()).append(";");
        }

        key.append("CABIN:").append(flight.getCabinClass());

        return key.toString();
    }

    private String formatTimeForKey(String dateTimeStr) {
        if (dateTimeStr == null || dateTimeStr.length() < 13) {
            return dateTimeStr;
        }
        try {
            return dateTimeStr.substring(0, 13); // 精确到小时
        } catch (Exception e) {
            return dateTimeStr;
        }
    }

    public List<RoundTripFlightInfo> processFlightsWithTranslation(List<RoundTripFlightInfo> savedFlights, FlightSearchRequest request) {
        if (savedFlights == null || savedFlights.isEmpty()) {
            return savedFlights;
        }

        // 如果不需要翻译，直接返回
        if (!StringUtils.hasText(request.getLang()) || "zh".equals(request.getLang())) {
            return savedFlights;
        }

        try {
            log.info("开始并行翻译航班信息，数量: {}, 目标语言: {}", savedFlights.size(), request.getLang());
            long startTime = System.currentTimeMillis();

            // 收集所有需要翻译的文本
            List<String> allTexts = new ArrayList<>();
            List<Integer> textCounts = new ArrayList<>(); // 记录每个航班的文本数量

            for (RoundTripFlightInfo flight : savedFlights) {
                List<String> flightTexts = translationService.prepareTextsForTranslation(flight);
                allTexts.addAll(flightTexts);
                textCounts.add(flightTexts.size());
            }

            // 多线程批量翻译
            List<String> translatedTexts = translationService.batchTranslateTexts(allTexts, "zh", request.getLang());

            // 应用翻译结果到航班对象
            List<RoundTripFlightInfo> result = translateRoundFlight(savedFlights, translatedTexts, textCounts);

            long endTime = System.currentTimeMillis();
            log.info("多线程翻译完成，耗时: {}ms", endTime - startTime);

            return result;

        } catch (Exception e) {
            log.error("多语言处理失败，使用原始数据", e);
            return savedFlights;
        }
    }

    /**
     * 翻译单个航班信息
     */
    private List<RoundTripFlightInfo> translateRoundFlight(List<RoundTripFlightInfo> flights, List<String> translatedTexts, List<Integer> textCounts) {
        List<RoundTripFlightInfo> result = new ArrayList<>();
        int textIndex = 0;

        for (int i = 0; i < flights.size(); i++) {
            RoundTripFlightInfo flight = flights.get(i);
            int expectedTextCount = textCounts.get(i);

            // 检查翻译结果数量是否足够
            if (textIndex + expectedTextCount > translatedTexts.size()) {
                log.warn("翻译结果不足，航班 {} 使用原始数据", flight.getId());
                result.add(flight);
                continue;
            }

            try {

                // 去程信息
                flight.getOutboundFlight().setFlightNumber(translatedTexts.get(0));
                flight.getOutboundFlight().setAirline(translatedTexts.get(1));
                flight.getOutboundFlight().setDuration(translatedTexts.get(2));
                flight.getOutboundFlight().setDepartureAirport(translatedTexts.get(3));
                flight.getOutboundFlight().setArrivalAirport(translatedTexts.get(4));
                flight.getOutboundFlight().setDepartureCity(translatedTexts.get(5));
                flight.getOutboundFlight().setArrivalCity(translatedTexts.get(6));

                // 返程信息
                flight.getReturnFlight().setFlightNumber(translatedTexts.get(7));
                flight.getReturnFlight().setAirline(translatedTexts.get(8));
                flight.getReturnFlight().setDuration(translatedTexts.get(9));
                flight.getReturnFlight().setDepartureAirport(translatedTexts.get(10));
                flight.getReturnFlight().setArrivalAirport(translatedTexts.get(11));
                flight.getReturnFlight().setDepartureCity(translatedTexts.get(12));
                flight.getReturnFlight().setArrivalCity(translatedTexts.get(13));

                // 行李信息
                flight.setBaggageInfo(translatedTexts.get(14));
                flight.getOutboundFlight().setBaggageInfo(translatedTexts.get(14));
                flight.getReturnFlight().setBaggageInfo(translatedTexts.get(14));

                // 购买须知
                String[] split = translatedTexts.get(15).split("；");
                List<String> purchaseNotes = Arrays.stream(split)
                        .map(String::trim)
                        .toList();
                flight.setPurchaseNotes(purchaseNotes);
                flight.getOutboundFlight().setPurchaseNotes(purchaseNotes);
                flight.getReturnFlight().setPurchaseNotes(purchaseNotes);

                result.add(flight);
                textIndex += expectedTextCount;

            } catch (Exception e) {
                log.error("应用翻译结果失败，航班: {}", flight.getId(), e);
                result.add(flight);
                textIndex += expectedTextCount;
            }
        }
        return result;
    }
}